import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { NzImageService } from 'ng-zorro-antd/image';
import { EInvoiceService } from 'src/app/service/fee-enquiry/e-invoice.service';
import { FeeEnquiryService } from 'src/app/service/fee-enquiry/fee-enquiry.service';
import { MessageService } from 'src/app/service/message.service';
import { UsageCodeData, UserBindService } from 'src/app/service/user-bind.service';
import { downFile } from 'src/app/utils/utils';

@Component({
  selector: 'app-e-invoice',
  templateUrl: './e-invoice.component.html',
  styleUrls: ['./e-invoice.component.scss']
})
export class EInvoiceComponent implements OnInit {

  invflagState = {
    'N': { value: '未开票', color: 'orange' },
    'Y': { value: '已开票', color: 'green' },
  }
  title = '缴费记录'
  constructor(
    private userBind: UserBindService,
    private feeEnquiry: FeeEnquiryService,
    private message: MessageService,
    private route: ActivatedRoute,
    private eInvoice: EInvoiceService,
    private image: NzImageService,
    private http: HttpClient
  ) { }

  usageCode = ''
  address: string | undefined = ''
  ngOnInit(): void {
    this.route.data.subscribe(res => {
      this.title = res['breadcrumb']
      this.getUsageCodeList()
    })
  }

  usageCodeLoading = false
  usageCodeInfoList: UsageCodeData[] = []
  onUsageCodeChange(value: string){
    this.usageCode = value
    this.address = this.usageCodeInfoList.find(_ => _.usageCode === value)?.address
    this.getPayList()
  }
  getUsageCodeList(){
    this.usageCodeLoading = true;
    this.userBind._getBindList().subscribe({
      next: res => {
        this.usageCodeInfoList = res;
        this.initUsageCode(res[0]);
        this.usageCodeLoading = false;
      }, 
      error: error => {
        // this.util.createErrorMessage(error);
        this.usageCodeLoading = false;
      }}
    )
  }
  initUsageCode(item: UsageCodeData){
    this.usageCode = item.usageCode;
    this.address = item.address;
    this.getPayList();
  }

//   public class Invoice {
//     private String id;//记录id
//     private String code;//用水编号
//     private String billType;//票据类型
//     private String invoiceTime;//开票时间
//     private String invoicer;//开票人
//     private String serial;//发票流水号
//     private String invoiceName;//发票名称
//     private String invoiceNumber;//发票号码
//     private String invoiceCode;//发票代码
//     private String billAmount;//发票金额
// }
  cols = {
    "code":	"用水编号",
    "invoiceTime": "开票时间",
    "invoiceName":	"发票名称",
    "invoiceNumber":	"发票号码",
    "invoiceCode":	"发票代码",
    "billAmount":	"发票金额",
  }
  data: any[] = []
  dataLoading = false
  pageNumber = 1
  pageSize = 10
  total = 0
  getPayList(){
    this.dataLoading = true
    this.data = []
    // '00034987'
    this.feeEnquiry._getInvoiceList(this.usageCode).subscribe({
      next: res => {
        if(res && res.resultList){
          this.data = res.resultList
          this.total = res.totalNumber
        }
        this.dataLoading = false
      },
      error: error => {
        this.message.error('查询数据错误, 请稍后再试')
        this.dataLoading = false
      }
    })
  }

  goEInvoice(data: any){
    this.dataLoading = true
    this.eInvoice._applyEInvoice(data.pid, this.usageCode).subscribe({
      next: res => {
        console.log(res)
        this.dataLoading =false
      },
      error: error => {
        this.message.createErrorMessage(error)
        this.dataLoading = false
      }
    })
  }

  invoiceUrl = ''
  downloadUrl = ''
  invoiceModal = false
  viewInvoice(data: any){
    console.log(data)
    if(!data['url'] || data['url'] === 'null'){
      this.message.info('发票暂未开具，请稍后再试')
      return
    }

    this.dataLoading = true

    // this.downloadUrl = '/apps/gsxmcp/staticFile/test.pdf'
    // this.invoiceUrl = encodeURIComponent('/apps/gsxmcp/staticFile/test.pdf')
    // this.invoiceModal = true
    // this.dataLoading = false
    if(data){
      this.invoiceUrl = ''
      
      const invoiceUrl = data['url']
      const baseUrl = '/api/gsxmcp/cs/iv/v1.0/invoice/downloadInvoice?pdfUrl='
      this.downloadUrl = baseUrl + encodeURIComponent(invoiceUrl)
      this.invoiceUrl = encodeURIComponent(baseUrl + encodeURIComponent(invoiceUrl))
      // this.invoiceUrl = this.downloadUrl
      this.invoiceModal = true
    }
    this.dataLoading = false
    return
    this.eInvoice._applyEInvoice(data.pid, this.usageCode).subscribe({
      next: res => {
        console.log(res)
        if(res && res['data'] && res['data']['rtnMsg'] === '开票成功'){
          const invoiceUrl = res['data']['urls'][0]['downpath']
          const baseUrl = '/api/gsxmcp/cs/iv/v1.0/invoice/downloadInvoice?billid=null&pdfUrl='
          this.downloadUrl = baseUrl + invoiceUrl
          this.invoiceUrl = encodeURIComponent(baseUrl + invoiceUrl)
          this.invoiceModal = true
        }else{
          this.message.error(res['data']['rtnMsg'])
        }
        this.dataLoading = false
      },
      error: error => {
        this.message.createErrorMessage(error)
        this.dataLoading = false
      }
    })
  }
  downInvoice(data = null){
    if(data && data['url'] && data['url'] !== 'null'){
      const invoiceUrl = data['url']
      const baseUrl = '/api/gsxmcp/cs/iv/v1.0/invoice/downloadInvoice?pdfUrl='
      this.downloadUrl = baseUrl + encodeURIComponent(invoiceUrl)
    }

    if(!this.downloadUrl){
      this.message.info('发票暂未开具，请稍后再试')
      return
    }

    this.dataLoading = true
    this.http.get(this.downloadUrl, { responseType: 'blob' }).subscribe(res => {
      this.dataLoading = false
      downFile(res, '水费电子发票.pdf')
    }, error => {
      this.message.error(error)
      this.dataLoading = false
    })
  }

}
